/* 
1.qq授权码:QQ邮箱->设置->账户->POP3/SMTP服务开启->生成授权码
2.163授权码:设置->POP3/SMTP服务->生成授权码
3.平台配置信息:node_modules->nodemailer->lib->well-known->services.json
*/
const mailer = require('nodemailer')

//获得邮箱平台
function getEmailPlatform(email) {
    /^[a-z0-9]+([._-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9])+.{1,63}[a-z0-9]+$/.test(email)
    return RegExp.$2
}

//发送邮件   reject(1)表示不支持该邮件平台平台
function sendEmail(from, auth, to, subject, content) {
    return new Promise((resolve, reject) => {
        //邮箱配置对象
        let transporter
        //获得邮件发送平台
        let platform = getEmailPlatform(from)

        //不同平台配置对象不同
        if (platform == 'qq') {
            //qq和163配置不同
            transporter = mailer.createTransport({
                host: "smtp.qq.com",
                port: 465,
                secure: true,
                auth: { user: from, pass: auth }
            })
        } else if (platform == '163') {
            transporter = mailer.createTransport({
                host: "smtp.163.com",
                port: 465,
                secure: true,
                auth: { user: from, pass: auth }
            })
        } else {
            //不支持其它平台
            reject('不支持该平台')
        }

        //配置邮件内容
        let mailOptions = {
            from: `<${from}>`,
            to: to,
            //主题
            subject: subject,
            //内容
            html: content,
        };
        //发送邮件
        transporter.sendMail(mailOptions, (err, data) => {
            err ? reject(err) : resolve(data)
        })
    })
}

module.exports = {
    getEmailPlatform,
    sendEmail
}